package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"vpn_checkin"
)

func main() {
	var (
		loginUrl string
		req *http.Request
		err error
		client *http.Client
		resp *http.Response
		body []byte
		urlParams url.Values
		postParams *strings.Reader
		cookies []*http.Cookie
		cookie *http.Cookie
	)

	loginUrl = "https://www.cordcloud.biz/auth/login"

	urlParams = url.Values{}
	urlParams.Add("email",`171324316@qq.com`)
	urlParams.Add("passwd",`lhb1314.`)

	postParams = strings.NewReader(urlParams.Encode())

	client = &http.Client{}
	req,err = http.NewRequest("POST",loginUrl,postParams)
	if err != nil {
		log.Printf("连接VPN失败 " + err.Error())
		return
	}



	req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	resp,err = client.Do(req)
	defer resp.Body.Close()
	if err != nil {
		log.Printf("请求VPN地址登陆失败:" + err.Error())
		return
	}
	body,err = io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("解析登陆返回参数失败 " + err.Error())
	}
	LoginRes := &vpn_checkin.Res{}
	err = json.Unmarshal(body,LoginRes)
	if err != nil {
		log.Printf("反序列话登陆返回参数失败: " + err.Error())
		return
	}
	body,err = zhToUnicode(body)
	if err != nil {
		log.Printf("unicode转中文失败: " + err.Error())
		return
	}
	if LoginRes.Ret != 1 {
		log.Printf("登陆返回参数有问题:" + string(body))
		return
	}

	fmt.Println("登陆成功,返回参数为:" + string(body))

	cookies = resp.Cookies()

	// 请求签到接口
	var (
		checkInUrl string
		checkInRes *vpn_checkin.Res
	)
	checkInUrl = "https://www.cordcloud.biz/user/checkin"

	req,err = http.NewRequest("POST",checkInUrl, nil)
	if err != nil {
		log.Printf("构建签到请求失败:" + err.Error())
		return
	}
	for _, cookie = range cookies {
		req.AddCookie(cookie)
	}
	resp,err = client.Do(req)
	defer resp.Body.Close()
	if err != nil {
		log.Printf("请求签到接口失败:" +err.Error())
		return
	}

	body,err = io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("解析签到返回参数失败:" + err.Error())
		return
	}

	checkInRes = &vpn_checkin.Res{}

	err = json.Unmarshal(body,checkInRes)
	if err != nil {
		log.Printf("签到反序列化失败:" + err.Error())
	}
	body,err = zhToUnicode(body)
	if err != nil {
		log.Printf("签到unicode转中文失败: " + err.Error())
		return
	}
	if checkInRes.Ret != 1 {
		fmt.Println("签到失败,返回参数: " + string(body))
		return
	}
	// 签到成功
	fmt.Println("签到成功,返回参数: " + string(body))

}

func zhToUnicode(raw []byte) ([]byte, error) {
	str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(raw)), `\\u`, `\u`, -1))
	if err != nil {
		return nil, err
	}
	return []byte(str), nil
}